//
//  GaodeMapViewController.m
//  EasyChat
//
//  Created by dllo on 16/6/21.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "GaodeMapViewController.h"
#import <iflyMSC/iflyMSC.h>

#define NAVCWidth self.navigationController.navigationBar.frame.size.width
#define NAVCheight self.navigationController.navigationBar.frame.size.height

@interface GaodeMapViewController ()<MAMapViewDelegate, AMapSearchDelegate,UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, UIScrollViewDelegate,IFlyRecognizerViewDelegate>
@property (nonatomic, retain) UITextField *searchTextfield;//搜索框
@property (nonatomic, retain) UIButton *voiceBtn;//语音按钮;
@property (nonatomic, retain) UIView *SearchAroundBtnsView;//附近搜索,按钮展示区
@property (nonatomic, retain) NSMutableArray *poiClassArr;//附近搜索类别数组
@property (nonatomic, retain) MAMapView *mapView;//地图对象属性
@property (nonatomic, retain) AMapSearchAPI *search;//搜索对象属性
@property (nonatomic, retain) CLLocation *currentLocation;//当前位置
@property (nonatomic, retain) UIButton *locationButton;//开始定位的按钮
@property (nonatomic, retain) CLGeocoder *geoC;//地理编码
@property (nonatomic, retain) MAPointAnnotation *destinationPoint;//长按地图出来的目的地大头针
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSArray *pois;//获取的周围兴趣点集合数组
@property (nonatomic, retain) NSArray *pathPolylines;//路线数组
@property (nonatomic, retain) IFlyRecognizerView *iflyRecognizerView;
@end

@implementation GaodeMapViewController

#pragma mark - 懒加载
- (CLGeocoder *)geoC
{
    if (!_geoC) {
        _geoC = [[CLGeocoder alloc] init];
    }
    return _geoC;
}
- (void)dealloc
{
    [_searchTextfield release];
    [_voiceBtn release];
    [_mapView release];
    [_SearchAroundBtnsView release];
    [_search release];
    [_currentLocation release];
    [_locationButton release];
    [_geoC release];
    [_destinationPoint release];
    [_tableView release];
    [_pois release];
    [_pathPolylines release];
    [_iflyRecognizerView release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setBarTintColor:[UIColor clearColor]];
//    self.navigationController.navigationBar.backgroundColor = [UIColor blueColor];
    self.navigationController.navigationBar.translucent = YES;
    
    //初始化
    [self initAttriButes];
    //创建地图
    [self createMapView];
    //创建titleView
    [self createSearchTextField];
    //创建附近搜索按钮展示栏
    [self createSearchAroundBtns];
    //创建定位按钮
    [self initLocationButton];
    //初始化搜索对象
    [self initSearch];
    //附近搜索结果展示
    [self initTableView];
    // 高德地图的apikey
    [AMapServices sharedServices].apiKey = @"7aef23ea3ac8f02319ca8eaf5a41950d";
    
    // 科大讯飞********************************
    // 初始化 识别身份 它是唯一的 初始化时必须要传入APPid
    NSString *initstring = [NSString stringWithFormat:@"appid=%@",@"57693e78"];
    [IFlySpeechUtility createUtility:initstring];
    
       // 科大讯飞
    [self iflyRecognize];
    
    //返回按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(leftBtnAction:)];
    
    //监听键盘弹起
    //通知中心
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    //键盘回收
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

#pragma mark - 创建对象
- (void)initAttriButes
{
    self.pois = nil;
}
- (void)createMapView
{
    
    // 地图
    self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    self.mapView.delegate = self;
    [_mapView release];
    
    //罗盘的位置
    self.mapView.compassOrigin = CGPointMake(self.mapView.compassOrigin.x, NAVCheight * 2);
    // 比例尺的位置
    self.mapView.compassOrigin = CGPointMake(self.mapView.scaleOrigin.x, NAVCheight * 2);
    
    [self.view addSubview:self.mapView];
    
    // 打开定位
    self.mapView.showsUserLocation = YES;
    
    // 设置跟踪模式
    [self.mapView setUserTrackingMode:MAUserTrackingModeFollowWithHeading animated:YES];
}
/*
 视图中的几个view的弹出收回逻辑
 1.显示附近搜索的tableview,选择展示栏 在初始状态被收起
 2.开始编辑textfield的时候,键盘弹出,选择展示栏弹出
 3.点击选择状态栏上的按钮时,键盘被收回,选择展示栏被收回(显示附近搜索的tableview)
 4.键盘收回,选择状态栏被收起,
 显示附近搜索的tableview判断附近搜索的pois数组是否为nil,为nil则收起, 不为nil则弹出
 5.键盘弹出,显示附近搜索的tableview被收起,判断附近搜索的pois数组是否为nil,为nil则不显示按钮, 不为nil则显示按钮, 点击可以让显示附近搜索的tableview被显示
 6.显示附近搜索的tableview显示, 键盘回收;
 7.viewtouch,键盘回收,显示附近搜索的tableview回收,判断附近搜索的pois数组是否为nil,为nil则不显示按钮, 不为nil则显示按钮, 点击可以让显示附近搜索的tableview被显示
 */

- (void)createSearchTextField
{
    UIView *naTitleView = [[UIView alloc] initWithFrame:CGRectMake(0, 5, NAVCWidth - 50, NAVCheight - 10)];
    naTitleView.backgroundColor = [UIColor clearColor];
    
    // 搜索框
    self.searchTextfield = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, naTitleView.frame.size.width / 5 * 4, naTitleView.frame.size.height)];
    self.searchTextfield.backgroundColor = [UIColor clearColor];
    self.searchTextfield.layer.borderWidth = 1;
    self.searchTextfield.layer.cornerRadius = 10;
    self.searchTextfield.layer.borderColor = [[UIColor grayColor] CGColor];

    // 设置字体的颜色
    self.searchTextfield.textColor = [UIColor grayColor];
    // 设置placeholder的颜色
    UIColor *color = [UIColor lightTextColor];
    self.searchTextfield.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"  请输入地址......" attributes:@{NSForegroundColorAttributeName: color}];
    // 设置placeholder的字体大小
    [self.searchTextfield setValue:[UIFont systemFontOfSize:15] forKeyPath:@"_placeholderLabel.font"];
    [naTitleView addSubview:self.searchTextfield];
    [_searchTextfield release];
    
    // 成为代理人
    self.searchTextfield.delegate = self;
    self.searchTextfield.returnKeyType = UIReturnKeySearch;
    
    // 语音按钮
    self.voiceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.voiceBtn.frame = CGRectMake(naTitleView.frame.size.width / 5 * 4, 0, naTitleView.frame.size.width / 6, naTitleView.frame.size.height);
    self.voiceBtn.backgroundColor = [UIColor clearColor];
    [self.voiceBtn setBackgroundImage:[UIImage imageNamed:@"Unknown-9"] forState:UIControlStateNormal];
    [self.voiceBtn addTarget:self action:@selector(voiceBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [naTitleView addSubview:self.voiceBtn];
    [_voiceBtn release];
    self.navigationItem.titleView = naTitleView;
    [naTitleView release];
    
}
- (void)createSearchAroundBtns
{
    self.SearchAroundBtnsView = [[UIView alloc] initWithFrame:CGRectMake(0, - NAVCheight - 20, WIDTH, NAVCheight + 20)];
    self.SearchAroundBtnsView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.SearchAroundBtnsView];
    [_SearchAroundBtnsView release];
    
    self.poiClassArr = [NSMutableArray arrayWithObjects:@"学校", @"公交车站", @"餐饮服务", @"购物服务", @"酒店公寓", @"风景名胜", @"商务住宅", @"政府机构", nil];
    UIScrollView *btnScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 10, WIDTH, NAVCheight)];
    btnScrollView.delegate = self;
    for (int i = 0; i < self.poiClassArr.count; i++) {
        UIButton *btnX = [UIButton buttonWithType:UIButtonTypeCustom];
        btnX.frame = CGRectMake(5 + NAVCheight * 2 * i, 5, NAVCheight * 2 - 10, NAVCheight - 10);
        btnX.backgroundColor = [UIColor whiteColor];
        // tag值可以获取self.poiClassArr中的keyWord
        btnX.tag = 10000 + i;
        [btnX setTitle:[self.poiClassArr objectAtIndex:i] forState:UIControlStateNormal];
        [btnX setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        btnX.layer.borderWidth = 1;
        btnX.layer.borderColor = [[UIColor grayColor]CGColor];
        btnX.layer.masksToBounds = YES;
        btnX.layer.cornerRadius = 5;
        
        [btnX addTarget:self action:@selector(btnXAction:) forControlEvents:UIControlEventTouchUpInside];
        [btnScrollView addSubview:btnX];
    }
    btnScrollView.contentSize = CGSizeMake(NAVCheight * 2 * self.poiClassArr.count, 0);
    [self.SearchAroundBtnsView addSubview:btnScrollView];
    [btnScrollView release];
}

- (void)initSearch
{
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
}

//附近搜索展示结果
- (void)initTableView
{
    CGFloat halfHeight = CGRectGetHeight(self.view.bounds) * 0.5;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.view.bounds), CGRectGetWidth(self.view.bounds), halfHeight) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [self.view addSubview:_tableView];
}
#pragma mark-- button
//创建按钮图标
-(void)initLocationButton{
    self.locationButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.locationButton.frame = CGRectMake(20, CGRectGetHeight(self.mapView.bounds) - 80, 30, 30);
    self.locationButton.backgroundColor = [UIColor whiteColor];
    self.locationButton.layer.masksToBounds = YES;
    self.locationButton.layer.cornerRadius = 5;
    [self.locationButton addTarget:self action:@selector(locateAction) forControlEvents:UIControlEventTouchUpInside];
    [self.locationButton setImage:[UIImage imageNamed:@"location_yes"] forState:UIControlStateNormal];
    [self.mapView addSubview:self.locationButton];
    
    
    //路线按钮
    UIButton *pathButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    pathButton.frame = CGRectMake(20, CGRectGetHeight(self.mapView.bounds) - 140, 30, 30);
    pathButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
    pathButton.backgroundColor = [UIColor whiteColor];
    [pathButton setImage:[UIImage imageNamed:@"path"] forState:UIControlStateNormal];
    
    [pathButton addTarget:self action:@selector(pathAction) forControlEvents:UIControlEventTouchUpInside];
    
    [_mapView addSubview:pathButton];
}
#pragma mark--MAMapViewDelegate
//当位置更新时,会进行定位回调,通过回调函数,回去到定位点的经纬度
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation{
    
    if (updatingLocation) {
        //NSLog(@"latitude : %f,longitude: %f",userLocation.coordinate.latitude,userLocation.coordinate.longitude);
        self.currentLocation = [userLocation.location copy];
        
    }
}
//替换定位按钮图标:使用mapView回调方法监听定位模式状态
-(void)mapView:(MAMapView *)mapView didChangeUserTrackingMode:(MAUserTrackingMode)mode animated:(BOOL)animated{
    if (mode ==  MAUserTrackingModeNone) {
        [self.locationButton setImage:[UIImage imageNamed:@"location_no"] forState:UIControlStateNormal];
    }else{
        
        [self.locationButton setImage:[UIImage imageNamed:@"location_yes"]forState:UIControlStateNormal];
        
    }
    
    
}
//重写方法, 自定义大头针
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation

{
    //不定制自己位置的标注视图
    
    if ( [annotation isKindOfClass:[MAUserLocation class]]) {
        
        return nil;
    }
    // 1、自带的标注视图
    
    MAPinAnnotationView *pinAnnView = (MAPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"ID"];
    
    if ( !pinAnnView ) {
        
        pinAnnView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"ID"];
    }
    
    // 是否可弹出视图
    pinAnnView.canShowCallout = YES;
    
    // 设置掉落动画
    pinAnnView.animatesDrop = YES;
    
    // 设置标注颜色
    
    pinAnnView.pinColor = MAPinAnnotationColorGreen;
    // 设置左视图
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    
    leftView.backgroundColor = [UIColor blueColor];
    
    pinAnnView.leftCalloutAccessoryView = leftView;
    
    //设置右视图
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    
    pinAnnView.rightCalloutAccessoryView = rightBtn;
    return pinAnnView;
    
}
//在选中用户位置annotation时弹出当前地址
-(void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view{
    // 选中定位annotation的时候进行逆地理编码查询
    if ([view.annotation isKindOfClass:[MAUserLocation class]]) {
        
        [self reGeoAction];
    }
}
//长按地图,添加大头针
- (void)mapView:(MAMapView *)mapView didLongPressedAtCoordinate:(CLLocationCoordinate2D)coordinate
{
    
    
    //将路线清空
    if (self.pathPolylines != nil) {
        
        [self.mapView removeOverlays:self.pathPolylines];
        self.pathPolylines = nil;
        
    }
        // 添加标注
    if (_destinationPoint != nil)
    {
        // 清理
        [_mapView removeAnnotation:_destinationPoint];
        _destinationPoint = nil;
        
        //        [_mapView removeOverlays:_pathPolylines];
        //        _pathPolylines = nil;
    }
    
    //在该点添加一个大头针(标注)
    
    self.destinationPoint = [[MAPointAnnotation alloc] init];
    
    self.destinationPoint.coordinate = coordinate;
    
    //反地理编码,获取当前位置的信息
    CLLocation *location = [[CLLocation alloc] initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    [self.geoC reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        //地标对象
        CLPlacemark *pl = [placemarks firstObject];
        
        //取详细地址
        NSString *name = pl.name;
        
        //获取城市
        NSString *city = pl.locality;
        
        self.destinationPoint.title = city;
        self.destinationPoint.subtitle = name;
        
        
        
    }];
    
    //将显示的中心切换到长按的地方
    // b) 设置缩放
    MACoordinateSpan span = MACoordinateSpanMake(0.001, 0.001);
    
    // c) 设置区域
    MACoordinateRegion region = MACoordinateRegionMake(coordinate, span);
    // d) 显示区域
    //        _mapView.region = region;
    [self.mapView setRegion:region animated:YES];
    
    [_mapView addAnnotation:self.destinationPoint];
    [_destinationPoint release];
}
//逆地理编码 发起搜索请求
-(void)reGeoAction{
    if (self.currentLocation) {
        AMapReGeocodeSearchRequest *request = [[AMapReGeocodeSearchRequest alloc] init];
        request.location = [AMapGeoPoint locationWithLatitude:self.currentLocation.coordinate.latitude longitude:self.currentLocation.coordinate.longitude];
        [self.search AMapReGoecodeSearch:request];
    }
    
}
//绘制路线的方法:1.添加polyline 2. 实现MAMapView回调
-(MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay{
    if ([overlay isKindOfClass:[MAPolyline class]]) {
        MAPolylineRenderer *polylineRe = [[MAPolylineRenderer alloc] initWithOverlay:overlay];
        polylineRe.strokeColor = [UIColor blueColor];
        polylineRe.lineWidth = 4;
        
        return polylineRe;
        
    }
    
    return nil;
}
#pragma mark - AMapSearchDelegate
//逆地理编码
//搜索回调
//搜索失败
- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error{
    
    NSLog(@"request : %@, error: %@", request, error);
    
}
//搜索成功
-(void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response{
    NSString *title = response.regeocode.addressComponent.city;
    if (title.length == 0) {
        title = response.regeocode.addressComponent.province;
    }
    
    
    self.mapView.userLocation.title = title;
    self.mapView.userLocation.subtitle = response.regeocode.formattedAddress;
    
}
//搜索周边请求
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response{
    if (response.pois.count == 0) {
        
        //弹出提示框--地点输入错误
        //        NSLog(@"地点输入错误");
        
        //添加提示框
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"网络不好或地点输入错误" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        [self presentViewController:alertController animated:YES completion:^{
            
            [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(hideUIAlertController) userInfo:nil repeats:NO];
            
        }];
        
    }else{
        
        self.pois = response.pois;
        
        [self.tableView reloadData];
        
        // 清空标注
        [self.mapView removeAnnotation:self.destinationPoint];
        
    }
    
    
    //*********//
    //回收键盘
    [self.searchTextfield resignFirstResponder];
    
    
}
//路线请求
- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response{
    
    if(response.route == nil){
        return;
    }
    
    if (response.count > 0)
    {
        
        [self.mapView removeOverlays:self.pathPolylines];
        self.pathPolylines = nil;
        
        
        // 只显示第一条
        self.pathPolylines = [self polylinesForPath:response.route.paths[0]];
        [self.mapView addOverlays:_pathPolylines];
        
        [self.mapView showAnnotations:@[_destinationPoint, _mapView.userLocation] animated:YES];
    }
}
- (void)leftBtnAction:(UIBarButtonItem *)isBtn
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}
//定位按钮的点击方法开启或关闭定位
-(void)locateAction{
    if (self.mapView.userTrackingMode != MAUserTrackingModeFollow) {
        [self.mapView setUserTrackingMode:MAUserTrackingModeFollowWithHeading animated:YES];
    }else{
        [self.mapView setUserTrackingMode:MAUserTrackingModeNone animated:YES];
        
    }
    
}
// 科大讯飞语音识别
- (void)iflyRecognize
{
    //初始化语音识别控件
    self.iflyRecognizerView = [[IFlyRecognizerView alloc] initWithCenter:self.view.center];
    self.iflyRecognizerView.delegate = self;
    //设置听写模式
    [self.iflyRecognizerView setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
    //设置是否返回标点符号
    [self.iflyRecognizerView setParameter:@"asrview.pcm " forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];
    [self.iflyRecognizerView setParameter:@"0" forKey:[IFlySpeechConstant ASR_PTT]];
    
    //设置音频来源为麦克风
    [self.iflyRecognizerView setParameter:IFLY_AUDIO_SOURCE_MIC forKey:@"audio_source"];
    
    //设置听写结果格式为plain  默认json
    [self.iflyRecognizerView setParameter:@"plain" forKey:[IFlySpeechConstant RESULT_TYPE]];
    
    
    [self.view addSubview:self.iflyRecognizerView];
    self.iflyRecognizerView.hidden = YES;
    [_iflyRecognizerView release];

}

//语音按钮
- (void)voiceBtnAction:(UIButton *)isButton{
    [self.searchTextfield resignFirstResponder];
    
    self.iflyRecognizerView.hidden = NO;
    
    //启动识别
    [self.iflyRecognizerView start];
}


-(void)onResult:(NSArray *)resultArray isLast:(BOOL)isLast{
    NSMutableString *result = [[NSMutableString alloc] init];
    NSDictionary *dic = [resultArray objectAtIndex:0];
    
    for (NSString *key in dic) {
        [result appendFormat:@"%@",key];
    }
    
    self.searchTextfield.text = [NSString stringWithFormat:@"%@%@",self.searchTextfield.text,result];
    
}

- (void)onError: (IFlySpeechError *) error{

    NSLog(@"科大错误:%@",error);
}

//附近搜索提示框里的按钮点击方法
- (void)btnXAction:(UIButton *)isButton{
    
    if (_currentLocation == nil || _search == nil)
    {
        NSLog(@"search failed");
        return;
    }
    
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    request.radius = 1000;
    request.location = [AMapGeoPoint locationWithLatitude:_currentLocation.coordinate.latitude longitude:_currentLocation.coordinate.longitude];
    request.keywords = [self.poiClassArr objectAtIndex:isButton.tag - 10000];
    // types属性表示限定搜索POI的类别，默认为：餐饮服务|商务住宅|生活服务
    // POI的类型共分为20种大类别，分别为：
    // 学校|公交车站|汽车维修|住宿|餐饮服务|购物服务|生活服务|体育休闲服务|
    // 医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|
    // 交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施
    //3.支持设置排序规则sortrule，可将返回的POI按照距离远近进行排序。<! 排序规则, 0-距离排序；1-综合排序, 默认1>
    request.sortrule = 0;
    
    [_search AMapPOIAroundSearch:request];
    [request release];
    //回收键盘
    //    [self.searchTextfield resignFirstResponder];
}
//路线按钮的点击方法
- (void)pathAction
{
    
    if (_destinationPoint == nil || _currentLocation == nil || _search == nil)
    {
        NSLog(@"path search failed");
        //添加提示框
        UIAlertController *AlertController = [UIAlertController alertControllerWithTitle:@"请设置好起始位置和目的地" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        [self presentViewController:AlertController animated:YES completion:^{
            
            [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(hideUIAlertController) userInfo:nil repeats:NO];
            
        }];
        
        return;
    }
    
    AMapWalkingRouteSearchRequest *request = [[AMapWalkingRouteSearchRequest alloc] init];
    
    // 设置为步行路径规划
    
    
    request.origin = [AMapGeoPoint locationWithLatitude:_currentLocation.coordinate.latitude longitude:_currentLocation.coordinate.longitude];
    request.destination = [AMapGeoPoint locationWithLatitude:_destinationPoint.coordinate.latitude longitude:_destinationPoint.coordinate.longitude];
    
    [_search AMapWalkingRouteSearch:request];
    
}


- (CGSize)offsetToContainRect:(CGRect)innerRect inRect:(CGRect)outerRect
{
    CGFloat nudgeRight = fmaxf(0, CGRectGetMinX(outerRect) - (CGRectGetMinX(innerRect)));
    CGFloat nudgeLeft = fminf(0, CGRectGetMaxX(outerRect) - (CGRectGetMaxX(innerRect)));
    CGFloat nudgeTop = fmaxf(0, CGRectGetMinY(outerRect) - (CGRectGetMinY(innerRect)));
    CGFloat nudgeBottom = fminf(0, CGRectGetMaxY(outerRect) - (CGRectGetMaxY(innerRect)));
    return CGSizeMake(nudgeLeft ?: nudgeRight, nudgeTop ?: nudgeBottom);
}
//解析经纬度串
- (CLLocationCoordinate2D *)coordinatesForString:(NSString *)string
                                 coordinateCount:(NSUInteger *)coordinateCount
                                      parseToken:(NSString *)token
{
    if (string == nil)
    {
        return NULL;
    }
    
    if (token == nil)
    {
        token = @",";
    }
    
    NSString *str = @"";
    if (![token isEqualToString:@","])
    {
        str = [string stringByReplacingOccurrencesOfString:token withString:@","];
    }
    
    else
    {
        str = [NSString stringWithString:string];
    }
    
    NSArray *components = [str componentsSeparatedByString:@","];
    NSUInteger count = [components count] / 2;
    if (coordinateCount != NULL)
    {
        *coordinateCount = count;
    }
    CLLocationCoordinate2D *coordinates = (CLLocationCoordinate2D*)malloc(count * sizeof(CLLocationCoordinate2D));
    
    for (int i = 0; i < count; i++)
    {
        coordinates[i].longitude = [[components objectAtIndex:2 * i]     doubleValue];
        coordinates[i].latitude  = [[components objectAtIndex:2 * i + 1] doubleValue];
    }
    
    return coordinates;
}
//路线解析方法
- (NSArray *)polylinesForPath:(AMapPath *)path
{
    if (path == nil || path.steps.count == 0)
    {
        return nil;
    }
    
    NSMutableArray *polylines = [NSMutableArray array];
    
    [path.steps enumerateObjectsUsingBlock:^(AMapStep *step, NSUInteger idx, BOOL *stop) {
        
        NSUInteger count = 0;
        CLLocationCoordinate2D *coordinates = [self coordinatesForString:step.polyline
                                                         coordinateCount:&count
                                                              parseToken:@";"];
        
        MAPolyline *polyline = [MAPolyline polylineWithCoordinates:coordinates count:count];
        [polylines addObject:polyline];
        
        free(coordinates), coordinates = NULL;
    }];
    
    return polylines;
}
#pragma mark - UITableViewDataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cellIdentifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
    }
    
    
    AMapPOI *poi = _pois[indexPath.row];
    
    cell.textLabel.text = poi.name;
    
    //根据经纬度计算两点之间的距离
    //范围搜索的直接用poi.distance,关键字搜索的需要用经纬度计算
    double distance = 0;
    if (poi.distance != 0) {
        distance = poi.distance;
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ 距离:%.2lf米", poi.address, distance];
    }else{
        CLLocation *newLocation = [[CLLocation alloc]initWithLatitude:poi.location.latitude longitude:poi.location.longitude];
        distance = [newLocation distanceFromLocation:self.currentLocation];
        if (distance > 1000) {
            distance = distance / 1000;
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ 距离:%.2lf千米", poi.address, distance];
        }else{
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ 距离:%.2lf米", poi.address, distance];
        }
    }
    
    return cell;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _pois.count;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    // 为点击的poi点添加标注
    AMapPOI *poi = _pois[indexPath.row];
    
    // 添加标注
    if (_destinationPoint != nil)
    {
        // 清理
        [_mapView removeAnnotation:_destinationPoint];
        _destinationPoint = nil;
    }
    
    self.destinationPoint = [[MAPointAnnotation alloc] init];
    self.destinationPoint.coordinate = CLLocationCoordinate2DMake(poi.location.latitude, poi.location.longitude);
    self.destinationPoint.title =poi.name;
    //根据经纬度计算两点之间的距离
    //范围搜索的直接用poi.distance,关键字搜索的需要用经纬度计算
    double distance = 0;
    if (poi.distance) {
        distance = poi.distance;
        self.destinationPoint.subtitle = [NSString stringWithFormat:@"%@ 距离:%.2lf米", poi.address, distance];
    }else{
        CLLocation *newLocation = [[CLLocation alloc]initWithLatitude:poi.location.latitude longitude:poi.location.longitude];
        distance = [newLocation distanceFromLocation:self.currentLocation];
        if (distance > 1000) {
            
            distance = distance / 1000;
            self.destinationPoint.subtitle = [NSString stringWithFormat:@"%@ 距离:%.2lf千米", poi.address, distance];
        }else{
            self.destinationPoint.subtitle = [NSString stringWithFormat:@"%@ 距离:%.2lf米", poi.address, distance];
        }
    }
    //将显示的中心切换到长按的地方
    // b) 设置缩放
    MACoordinateSpan span = MACoordinateSpanMake(0.001, 0.001);
    
    // c) 设置区域
    MACoordinateRegion region = MACoordinateRegionMake(self.destinationPoint.coordinate, span);
    // d) 显示区域
    _mapView.region = region;
    
    [self.mapView addAnnotation:self.destinationPoint];
    
}
#pragma mark--UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    //进行关键字搜索
    
    AMapPOIKeywordsSearchRequest *request = [[AMapPOIKeywordsSearchRequest alloc]init];
    //搜索地点关键字
    request.keywords = self.searchTextfield.text;
    //是否返回拓展信息
    request.requireExtension = YES;
    request.city = @"全国";
    //关键字搜索没有这个属性
    //将返回的POI按照距离远近进行排序<! 排序规则, 0-距离排序；1-综合排序, 默认1>
    //    request.sortrule = 0;
    [self.search AMapPOIKeywordsSearch:request];
    //回收键盘
        [textField resignFirstResponder];
    
    return YES;
}
#pragma mark--viewDelegate
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [UIView animateWithDuration:0.2 animations:^{
        
        self.tableView.frame = CGRectMake(0, CGRectGetHeight(self.view.bounds), CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) * 0.5);
        if (self.pois != nil) {
            
            //显示一个按钮,点击让tableview出来
        }
        
    }];
    
    [self.searchTextfield resignFirstResponder];
}

- (void)keyBoardWillShow:(NSNotification *)notifi
{
    // 将路线清空
    if (self.pathPolylines != nil) {
        [self.mapView removeOverlays:self.pathPolylines];
        self.pathPolylines = nil;
    }
    // 将按钮清空
    if (self.destinationPoint != nil) {
        [self.mapView removeAnnotation:self.destinationPoint];
        self.destinationPoint = nil;
    }
    [UIView animateWithDuration:0.2 animations:^{
        self.SearchAroundBtnsView.frame = CGRectMake(0, 20 + NAVCheight, WIDTH, NAVCheight + 20);
        
        // 坐标
        self.tableView.frame = CGRectMake(0, CGRectGetHeight(self.view.bounds), CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) * 0.5);
        
    }];
}
- (void)keyBoardWillHide:(NSNotification *)notifi
{
    [UIView animateWithDuration:0.2 animations:^{
        
        self.SearchAroundBtnsView.frame = CGRectMake(0, - NAVCheight - 20, WIDTH, NAVCheight + 20);
        
        if (self.pois != nil) {
            
            self.tableView.frame = CGRectMake(0, CGRectGetHeight(self.view.bounds) * 0.5, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) * 0.5);
        }
    }];
    
}
//提示框自动消失计时器方法
-(void)hideUIAlertController{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    
}
- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
}
@end
